const app = getApp()
import { index as design } from '../../api/design'
import { index, clear, change, remove } from '../../api/cart'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

Page({
  data: {
    back: true,
    title: '购物车',
    loading: true,
    submitLoading: false,
    clearLoading: false,
    loadmore: false,
    login: false,
    list: [],
    failure: [],
    tip: false,
    all: false, // 是否全选
    total: 0, // 合计价格
    count: 0, // 购物车商品合计
    edit: false,
    design: [],
    abnor: {
      title: '购物车还是空的哦！',
      button: ''
    }
  },
  onLoad (options) {
    this.setData({ loading: true })
    design('cart').then(res => {
      this.setData({ design: res.data })
    })
      .finally(() => {
        this.setData({ loading: false })
      })
  },
  onShow () {
    if (app.login()) {
      const abnor = this.data.abnor
      abnor.title = '购物车还是空的哦~'
      abnor.button = ''

      this.setData({
        loading: true,
        all: false,
        total: 0,
        abnor: abnor
      })

      index().then(res => {
        this.getList(res.data.list)
        this.getFailureList(res.data.failure)
        this.setData({
          count: res.data.total
        })
      })
        .finally(() => {
          this.setData({ loading: false })
        })
    } else {
      const abnor = this.data.abnor
      abnor.title = '您还没有登录！'
      abnor.button = '立即登录'
      this.setData({ abnor: abnor })
    }
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () {},

  // ===================methon================

  getList (res) {
    const list = res
    list.forEach(item => {
      item.sales_price_discount = (item.sales_price - item.sku.sales_price).toFixed(2),
      item.disabled = item.quantity > item.sku.stock,
      item.logistics = [item.goods.is_express, item.goods.is_local, item.goods.is_fetch]
    })
    this.setData({ list: list })
  },

  getFailureList (res) {
    this.setData({ failure: res })
  },

  edit () {
    const list = this.data.list
    const edit = !this.data.edit
    list.forEach(item => {
      item.checked = false
      edit ? item.disabled = false : item.disabled = item.quantity > item.sku.stock
    })
    this.setData({
      all: false,
      list: list,
      edit: edit
    })
  },

  /**
   * 选择单个商品
   */
  checkOne (event) {
    const list = this.data.list
    list.forEach(item => {
      if (item.goods_sku_id == event.currentTarget.dataset.id) {
        item.checked = !item.checked
      }
    })
    
    this.setData({
      list: list,
      all: false
    })
    this.compute()
  },

  /**
   * 选择全部商品
   */
  checkAll () {
    const list = this.data.list
    list.forEach(item => {
      if (!item.disabled) {
        item.checked = !this.data.all
      }
    })
    this.setData({
      all: !this.data.all,
      list: list
    })
    this.compute()
  },

  /**
   * 改变商品数量
   */
  update (event) {
    const id = event.currentTarget.dataset.id
    let quantity = event.detail
    let count = 0
    const list = this.data.list
    
    wx.showLoading({ title: '加载中' })
    change({ id: id, quantity: quantity }).then(res => {
      list.forEach(item => {
        if (item.id == id) {
          item.quantity = event.detail
          count += event.detail
        } else {
          count += item.quantity
        }
      })
      this.setData({
        list: list,
        count: count
      })
      this.compute()
    })
      .catch(e => {
        app.toast(e.msg)
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  /**
   * 计算总价
   */
  compute () {
    let total = 0
    this.data.list.forEach(item => {
      if (item.checked) {
        total += item.sku.sales_price * item.quantity
      }
    })
    this.setData({ total: total * 100 })
  },

  clear () {
    const that = this
    that.setData({ clearLoading: true })

    clear().then(res => {
      app.toast('已清空失效商品', function () {
        that.setData({
          failure: []
        })
      }, 'success')
    })
      .finally(() => {
        that.setData({
          clearLoading: false
        })
      })
  },

  remove () {
    const id = []
    const list = []
    let count = []
    const that = this
    that.data.list.forEach(item => {
      if (item.checked) {
        id.push(item.id)
        count += parseInt(item.quantity)
      } else {
        list.push(item)
      }
    })
    Dialog.confirm({
      message: '确定删除这个商品吗？'
    }).then(() => {
      remove(id.toString()).then(res => {
        app.toast('删除成功', function () {
          that.setData({
            list: list,
            all: false,
            count: that.data.count - count
          })
        }, 'success')
      })
    }).catch(() => {})
  },

  submit () {
    const sku = []
    this.data.list.forEach(item => {
      if (item.checked && item.sku.stock >= item.quantity) {
        sku.push({
          id: item.goods_sku_id,
          quantity: item.quantity
        })
      }
    })
    if (sku.length == 0) {
      app.toast('请选择商品下单！')
      return false
    }
    wx.setStorageSync('sku', sku)
    app.redirect('/pages/order/confirm/index')
  },

  redirect (event) {
    app.redirect('/pages/goods/detail/index?id=' + event.currentTarget.dataset.id)
  },

  onAbnor () {
    this.setData({ login: true })
  }
})